import sympy as sp
from sympy import diff, Derivative

# 定义符号变量
x, y= sp.symbols('x y')

# 一阶导数
f = x**3 + 2*x**2 + x
df = diff(f, x)
print("一阶导数:", df) # 一阶导数: 3*x**2 + 4*x + 1

# 高阶导数
d2f = diff(f, x, 2) # 二阶导数: 2*(3*x + 2)
print("二阶导数:", d2f)

# 偏导数
g = x**2 * y + y**2
dg_dx = diff(g, x)
dg_dy = diff(g, y)
print("偏导数 ∂g/∂x:", dg_dx) # 偏导数 ∂g/∂x: 2*x*y
print("偏导数 ∂g/∂y:", dg_dy) # 偏导数 ∂g/∂y: x**2 + 2*y

# 创建偏导数表达式但不立即计算
deriv_expr = Derivative(g, x)
print("偏导数表达式:", deriv_expr) # 偏导数表达式: Derivative(x**2*y + y**2, x)
print("偏计算导数:", deriv_expr.doit()) # 计算偏导数: 2*x*y